/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package comp4081desktopapp;

/**
 *
 * @author Doug
 */
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.*;
import java.util.*;

public class ViewTherapy extends JFrame {
	JButton viewTherapyButton, viewFeedbackButton;
	JTextArea textArea;
	JScrollPane areaScrollPane;
	JMenu fileMenu;
	JMenuBar menuBar;
	JTextField patientIDNumber, therapyID;
	int patientIDValue = 0; //number from the textField
	int therapyIDValue = 0; //number for therapyID field
	boolean beginningLine = true; //used for aesthetic reasons in the textArea
	boolean viewTherapyDone = false;
public ViewTherapy() {
	super("View Therapy");
    setDefaultCloseOperation(EXIT_ON_CLOSE);

	fileMenu = createFileMenu(); //creating file menu
	menuBar = new JMenuBar();
	menuBar.add(fileMenu);
	setJMenuBar(menuBar);
	JPanel therapy = new JPanel(); //BIG PANEL to put everything in
	therapy.setLayout(new GridBagLayout());
	//therapy.setLayout(new BoxLayout(therapy, BoxLayout.X_AXIS));
	JPanel patientID = new JPanel();
	JLabel patientIDLabel = new JLabel("Patient ID:");
	patientID.add(patientIDLabel);
	JPanel textField = new JPanel();
	patientIDNumber = new JTextField(5);
	patientIDNumber.addActionListener(new PatientIDEntered());
	textField.add(patientIDNumber); //adding the patientIDField to the JPanel
	JPanel viewTherapy = new JPanel();
	viewTherapyButton = new JButton("View Therapy");
	viewTherapyButton.addActionListener(new AddTherapy());
	viewTherapy.add(viewTherapyButton); //adding button to viewTherapy panel
	JPanel patientLog = new JPanel();
	patientLog.setLayout(new BoxLayout(patientLog, BoxLayout.Y_AXIS));
	textArea = new JTextArea(10, 35);
	areaScrollPane = new JScrollPane(textArea);
    areaScrollPane.setHorizontalScrollBarPolicy(
    JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    areaScrollPane.setVerticalScrollBarPolicy(
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    //for View Feedback
    JPanel info = new JPanel(); //panel to put the jlabel on
    JLabel feedbackInfo = new JLabel("Please enter the therapy ID to send feedback on the therapy.");
    info.add(feedbackInfo);
    JPanel therapyIDTextField = new JPanel();
    therapyID = new JTextField(5);
    therapyID.addActionListener(new TherapyIDEntered());
    therapyIDTextField.add(therapyID);
    JPanel viewFeedback = new JPanel();
    viewFeedbackButton = new JButton("View Feedback");
    viewFeedbackButton.addActionListener(new ViewFeedback());
    viewFeedbackButton.setEnabled(false);
    viewFeedback.add(viewFeedbackButton);
    patientLog.add(areaScrollPane);
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    c.weightx = 0.0;
    therapy.add(patientID,c);
    therapy.add(textField,c);
    c.gridwidth = GridBagConstraints.REMAINDER;
    therapy.add(viewTherapy,c);
    c.weightx = 0.0;
    therapy.add(patientLog,c);
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.weightx =0.0;
    therapy.add(feedbackInfo,c);
    therapy.add(therapyIDTextField, c);
    therapy.add(viewFeedback, c);
    //therapy.add(patientID);
    //therapy.add(textField);
   // therapy.add(viewTherapy);
   // therapy.add(patientLog);
    getContentPane().add(therapy);
    pack();
}
public static void main(String[] args) {

   ViewTherapy viewTherapy = new ViewTherapy();
    viewTherapy.setVisible(true);
}
private JMenu createFileMenu()
{
    JMenu fileMenu = new JMenu("File");
    JMenuItem reset = new JMenuItem("Reset");
    reset.addActionListener(new Reset());
    fileMenu.add(reset);
    JMenuItem exit = new JMenuItem("Exit");
    exit.addActionListener(new Exit());
    fileMenu.add(exit);
    return fileMenu;
}
private class Exit implements ActionListener
{
       public void actionPerformed(ActionEvent e)
    {
        System.exit(0);
    }
}
private class Reset implements ActionListener //all selections will be removed
{
   public void actionPerformed(ActionEvent e)
    {
       	patientIDValue = 0;
        patientIDNumber.setText(""); //clearing text fields
        textArea.setText("");
        beginningLine = true;
        viewTherapyDone = false;
    }
}
private class PatientIDEntered implements ActionListener //for amount entered into text fields
{
    public void actionPerformed(ActionEvent e)
    {
        String text = patientIDNumber.getText();
        
        try {
            patientIDValue = Integer.parseInt(text);
        } catch (NumberFormatException a) {
            System.err.println("Invalid entry " + text);
        }
    }
}
private class AddTherapy implements ActionListener
{
	private ArrayList<Integer> therapyIDArrayList = new ArrayList<Integer>();
	private ArrayList<String> therapyDescriptionArrayList = new ArrayList<String>();
	private ArrayList<Double> therapySuccessPercentageArrayList = new ArrayList<Double>();
	private ArrayList<Integer> therapyUsageArrayList = new ArrayList<Integer>();
	 public void actionPerformed(ActionEvent e)
     {
		 if (beginningLine) { //if the therapies button is pressed
	         textArea.setText("List of therapies for patient #" + patientIDNumber.getText() + ":\n");
	     } else {
	                 textArea.setText(textArea.getText() + "\n" + "List of therapies for patient #" + patientIDNumber.getText() + ":\n");
	     }
		 beginningLine = false;
		 try { //this try/catch establishes connection and passes sql query, and the idea is to print the retun
				String connectURL = "jdbc:mysql://141.225.166.202:3306/test"; // test is the name of the database            
				Connection connection = null;// declare a connection by using Connection interface             
				Statement statement = null;// declare object of Statement interface that uses for executing sql statements.            
				
				String status = "";
				status = "connecting...\n";				
				System.out.println(status);
				Class.forName("com.mysql.jdbc.Driver").newInstance();// Load JBBC driver "com.mysql.jdbc.Driver".  
				connection = DriverManager.getConnection(connectURL, "root", "cancer11");// Create a connection by using getConnection()
				
				status = status + "...connected\n";				
				System.out.println(status);
				
				
				status = status + "creating statement\n";			
				System.out.println(status);
				/* createStatement() is used for create statement object that is used for sending sql statements
	            to the specified database. */
				statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                     ResultSet.CONCUR_UPDATABLE);
				
				status = status + "created statement\n";				
				System.out.println(status);
				status = status + "sending query\n";				
				System.out.println(status);
				
				

	            status = status + "query sent\n";
	            System.out.println(status);
	            
                    //set patient ID
                        String work = patientIDNumber.getText();
                        patientIDValue = new Integer(work);
	          //query therapyID
				ResultSet rsID = statement.executeQuery("SELECT THERAPY_ID from PATIENT_THERAPY where PATIENT_ID = " + patientIDNumber.getText() + "");
				rsID.first();
				therapyIDArrayList.clear();
				therapyIDArrayList.add(rsID.getInt(1)); //to get the first line
				while (rsID.next()) //to get subsequent lines
				{
					therapyIDArrayList.add(rsID.getInt(1));
				}
				System.out.println("therapyIDArrayList.size()" + therapyIDArrayList.size());
				rsID.close();
			  //query in the  Therapy table to get which therapies they are
				therapyDescriptionArrayList.clear(); //clearing because it needs to be empty each time the view therapy button is clicked
				for (int i = 0; i < therapyIDArrayList.size(); i++)
				{
				ResultSet rsTherapy = statement.executeQuery("SELECT DESCRIPTION FROM THERAPY WHERE ID = " + therapyIDArrayList.get(i) + "");
				rsTherapy.first();
					therapyDescriptionArrayList.add(rsTherapy.getString(1));
					
				System.out.println("therapyDescriptionArrayList.size()" + therapyDescriptionArrayList.size());
				
				//textArea.setText(textArea.getText() + therapyName + "\n");
				rsTherapy.close();
				}
				//getting successPercentage
				therapySuccessPercentageArrayList.clear();
				for (int i = 0; i < therapyIDArrayList.size(); i++)
				{
				ResultSet rsSuccessPercentage = statement.executeQuery("SELECT SUCCESS_PERCENTAGE FROM THERAPY WHERE ID = " + therapyIDArrayList.get(i) + "");
				rsSuccessPercentage.first();
				
					therapySuccessPercentageArrayList.add(rsSuccessPercentage.getDouble(1));
				rsSuccessPercentage.close();
				}
				//textArea.setText(textArea.getText() + "The success percentage is: " + successPercentage + "%\n");
				//getting number of uses
				therapyUsageArrayList.clear();
				for (int i = 0; i < therapyIDArrayList.size(); i++)
				{
				ResultSet rsUsageNum = statement.executeQuery("SELECT NUM_USE FROM THERAPY WHERE ID = " + therapyIDArrayList.get(i) + "");
				rsUsageNum.first();
					therapyUsageArrayList.add(rsUsageNum.getInt(1));
				rsUsageNum.close();
				}
				int n = 0;
				int o = 0;
				int p = 0;
				for (int i = 0; i < therapyIDArrayList.size(); i++)
				{
					textArea.setText(textArea.getText() + "The therapy ID is: " + therapyIDArrayList.get(i) + "\n");
					for (int j = 0; j < therapyDescriptionArrayList.size(); j++)
					{
						textArea.setText(textArea.getText() + "The therapy description is: " + therapyDescriptionArrayList.get(n) + "\n");
						n++;
						for (int k = 0; k < therapySuccessPercentageArrayList.size(); k++)
						{
						textArea.setText(textArea.getText() + "The success percentage is: " + therapySuccessPercentageArrayList.get(o) + "%\n");
						o++;
							for (int l = 0; l < therapyUsageArrayList.size(); l++)
							{
								textArea.setText(textArea.getText() + "The usage number is: " + therapyUsageArrayList.get(p) + "\n");
								p++;
								break;
							}
							break;
							
						}
						break;
					}
						
				}
				//textArea.setText(textArea.getText() + "The number of therapy uses is: " + usageNumber + "");
				statement.close();
				connection.close();
		 } catch (SQLException a) {
				textArea.setText("Error with database.");
				System.out.println(a.getMessage());
		 } catch (InstantiationException b) {
			 	textArea.setText("Instantiation Exception.");
			 	System.out.println(b.getMessage());
		 } catch (IllegalAccessException c) {
			 	textArea.setText("Illegal Access Exception.");
			 	System.out.println(c.getMessage());
		 } catch (ClassNotFoundException d) {
			 	textArea.setText("Class Not Found Exception.");
			 	System.out.println(d.getMessage()); 	
		 } 
				viewTherapyDone = true;
				viewFeedbackButton.setEnabled(true);
     }
}
private class TherapyIDEntered implements ActionListener //for amount entered into text fields
{
    public void actionPerformed(ActionEvent e)
    {
        String text = therapyID.getText();
        
        try {
            therapyIDValue = Integer.parseInt(text);
        } catch (NumberFormatException a) {
            System.err.println("Invalid entry " + text);
        }
    }
}
private class ViewFeedback implements ActionListener
{
	public void actionPerformed(ActionEvent e)
	{
            dispose();
            String[] args = {"1"};
            //Comp4081desktopApp desktopApp = new Comp4081desktopApp(getPID(),getTHID());
            Comp4081desktopApp desktopApp = new Comp4081desktopApp();
            System.out.println("THID "+getTHID());
            desktopApp.main(args,getPID(),getTHID());
	}
	
}

public int getPID(){
    return patientIDValue;
}
public int getTHID(){
    return Integer.parseInt(therapyID.getText());
}
}